import ExcelJS from 'exceljs'
import { isArrayBuffer } from '@microsoft/signalr/dist/esm/Utils'
import { isObject } from '@vueuse/core'

/**
 * 解析结果
 */
export interface ReadExcelFileType {
    headers: string[],
    data: string[][]
}

/**
 * 解析Excel
 */
export const readExcelFile = (file: File): Promise<ReadExcelFileType> => {
    return new Promise((resolve, reject) => {
        try {
            const reader = new FileReader()
            reader.onload = ({ target }: ProgressEvent<FileReader>) => {
                if (target && target.result && isArrayBuffer(target.result)) {
                    const buffer = target.result
                    const workbook = new ExcelJS.Workbook()
                    const data: string[][] = []
                    const result: ReadExcelFileType = {
                        headers: [],
                        data: []
                    }
                    // 2.解析buffer
                    workbook.xlsx.load(buffer).then((res) => {
                        // 遍历Excel中的每个工作表
                        workbook.eachSheet((sheet, sheetNumber) => {
                            // console.log('工作表 ' + sheetNumber);
                            // 遍历每个工作表中的每行数据
                            sheet.eachRow((row, rowNumber) => {
                                const cells: any[] = []
                                row.eachCell({ includeEmpty: true }, (cell) => {
                                    let value: any = ''
                                    // 判断单元格的类型
                                    //    6-公式 ;2-数值；3-字符串。
                                    if (cell.type == 6) {
                                        if (isObject(cell.result)) {
                                            value = ''
                                        } else {
                                            value = cell.result
                                        }
                                    } else {
                                        value = cell.value
                                    }
                                    cells.push(value)
                                    // console.log(`当前为第${rowNumber}行,第${colNumber}列,值为：${value}`)
                                });

                                if (rowNumber === 1) {
                                    result.headers = cells
                                } else {
                                    data.push(cells)
                                }
                            });
                        });

                        result.data = data

                        resolve(result)
                    })
                } else {
                    reject('Error reading the Excel file:');
                }
            }
            reader.readAsArrayBuffer(file)
        } catch (error) {
            reject('Error reading the Excel file:');
        }
    })
}